<template>
	<view class="root">
		<view class="header">
			<!-- <up-upload :fileList="fileList1" @afterRead="afterRead" name="1" multiple accept="video"
				:maxCount="10"></up-upload> -->
			<up-image width="152rpx" shape="circle" height="152rpx" style="border: 6rpx solid #fff; border-radius: 50%;"
				:src="config.http_host + userInfo.imageUrl" mode="scaleToFill"></up-image>
			<view style="flex: 1;">
				<view class="desc">
					<view class="name">
						<text>{{userInfo.nickName || ''}}</text>
					</view>
					<view class="time">
						<text>{{userInfo.registerDate}}</text>
					</view>
				</view>
				<view style="display: flex; align-items: center;">
					<view style="color: white; margin-top: 30rpx;">
						{{ visionData.gender==1?'男':'女' }}
					</view>
					<view style="color: white; margin-top: 30rpx; margin-left: 30rpx;">
						{{ getAgeFromString(visionData.birthdate)}}
					</view>
				</view>
			</view>
		</view>
		<view class="userinfo">
			<text>用户姓名 性别 年龄</text>
		</view>
		<view class="infocard">
			<view class="top">
				<view class="box">
					<view class="title">
						<text>球镜(S)</text>
					</view>
					<view class="value">
						<view class="content">
							<view class="subtitle">
								<text>左眼</text>
							</view>
							<view class="number">
								<text>{{visionData.sphericalLeft}}D</text>
							</view>
						</view>
						<view class="content">
							<view class="subtitle">
								<text>右眼</text>
							</view>
							<view class="number">
								<text>{{visionData.sphericalRight}}D</text>
							</view>
						</view>
					</view>
				</view>
				<view class="gapline"></view>
				<view class="box">
					<view class="title">
						<text>柱镜(S)</text>
					</view>
					<view class="value">
						<view class="content">
							<view class="subtitle">
								<text>左眼</text>
							</view>
							<view class="number">
								<text>{{visionData.cylindricalLeft}}D</text>
							</view>
						</view>
						<view class="content">
							<view class="subtitle">
								<text>右眼</text>
							</view>
							<view class="number">
								<text>{{visionData.cylindricalRight}}D</text>
							</view>
						</view>
					</view>
				</view>
				<view class="gapline"></view>
				<view class="box">
					<view class="title">
						<text>轴位(A)</text>
					</view>
					<view class="value">
						<view class="content">
							<view class="subtitle">
								<text>左眼</text>
							</view>
							<view class="number">
								<text>{{visionData.axisLeft}}°</text>
							</view>
						</view>
						<view class="content">
							<view class="subtitle">
								<text>右眼</text>
							</view>
							<view class="number">
								<text>{{visionData.axisRight}}°</text>
							</view>
						</view>
					</view>
				</view>
			</view>
			<view class="bottom">
				<view class="box">
					<view class="title">
						<text>裸眼视力</text>
					</view>
					<view class="value">
						<view class="content">
							<view class="subtitle">
								<text>左眼</text>
							</view>
							<view class="number">
								<text>{{visionData.scVaLeft}}</text>
							</view>
						</view>
						<view class="content">
							<view class="subtitle">
								<text>右眼</text>
							</view>
							<view class="number">
								<text>{{visionData.scVaRight}}</text>
							</view>
						</view>
					</view>
				</view>
				<view class="gapline"></view>
				<view class="box">
					<view class="title">
						<text>眼轴长度</text>
					</view>
					<view class="value">
						<view class="content">
							<view class="subtitle">
								<text>左眼</text>
							</view>
							<view class="number">
								<text>{{visionData.axialLengthLeft}}</text>
							</view>
						</view>
						<view class="content">
							<view class="subtitle">
								<text>右眼</text>
							</view>
							<view class="number">
								<text>{{visionData.axialLengthRight}}</text>
							</view>
						</view>
					</view>
				</view>
				<view class="gapline"></view>
				<view class="box">
					<view class="title">
						<text>角膜曲率</text>
					</view>
					<view class="value">
						<view class="content">
							<view class="subtitle">
								<text>左眼</text>
							</view>
							<view class="number">
								<text>{{visionData.keratometryLeft}}D</text>
							</view>
						</view>
						<view class="content">
							<view class="subtitle">
								<text>右眼</text>
							</view>
							<view class="number">
								<text>{{visionData.keratometryRight}}D</text>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<!-- <adcard style="margin-bottom: 75rpx;" title="专属管家"></adcard>
		<adcard style="margin-bottom: 75rpx;" title="专属医生"></adcard>
		<adcard style="margin-bottom: 177rpx;" title="专属视训师"></adcard> -->
		<view class="course">
			<view class="title">
				<text>今天的课程</text>
			</view>
			<view class="subtitle">
				<text>开始吧!</text>
			</view>
			<view class="course-card" @click="toDetails(item)" v-for="item in videoData" :key="item.id">
				<up-image width="123rpx" height="123rpx" style="border-radius: 7rpx;" :src="item.thUrl"
					mode="scaleToFill"></up-image>
				<view class="desc">
					<view class="name">
						<text>{{item.title}}</text>
					</view>
					<view class="tips">
						<text>{{item.describe || ''}}</text>
					</view>
				</view>
				<view class="status" v-if="item.detail">
					<up-icon name="checkmark" color="#fff" size="50rpx"></up-icon>
				</view>
				<view class="status" v-else>
					<up-icon name="play-right-fill" color="#fff" size="44rpx"></up-icon>
				</view>
			</view>
			<view style="margin-bottom: 40rpx;">
				<up-empty mode="list" text="课程列表为空" v-if="videoData.length === 0"></up-empty>
			</view>
		</view>
		<view class="badge-card">
			<view class="top">
				<image class="item" v-for="item in 4" src="@/static/badge.jpg" mode="scaleToFill"></image>
			</view>
			<!-- <view class="tips">
				<text>点击徽章查看今日份的海报哦！</text>
			</view> -->
			<view class="show-badge" @click="showBadge">
				<text>查看我的专属海报</text>
			</view>
		</view>
		<view class="nav animate__animated animate__fadeInUp">
			<view class="item" @click="changeNav(1)">
				<image :src="activeNav===1?'/static/a_home.png':'/static/home.png'" mode="scaleToFill"></image>
				<view :class="['bottomline',activeNav === 1? 'active' : '']"></view>
			</view>
			<view class="item" @click="changeNav(2)">
				<image :src="activeNav===2?'/static/a_user.png':'/static/user.png'" mode="scaleToFill"></image>
				<view :class="['bottomline',activeNav === 2? 'active' : '']"></view>
			</view>
		</view>
	</view>
	<up-overlay v-model:show="showBadgeRef">
		<view class="poster-popup-box">
			<view class="poster-popup">
				<view style="width: 550rpx;height: 800rpx; display: flex;flex-direction: column;justify-content: center;align-items: center;background-color: #eee;">
					<up-icon name="photo-fill" color="#0A9647" size="88rpx"></up-icon>
					<text style="font-size: 26rpx;margin-top: 8rpx;">暂无海报</text>
				</view>
				<!-- <image :src="posterImg" mode="widthFix" class="poster-img"></image> -->
			</view>
			<view class="action-btns">
				<view class="action-item" @click="saveLocal">
					<view style="margin-bottom: 10rpx; background-color: #fff; border-radius: 50%; padding: 10rpx;">
						<up-icon name="download" color="#07C160" size="28"></up-icon>
					</view>
					<text style="color: white; ">保存本地</text>
				</view>
				<view class="action-item" @click="shareFriend">
					<view style="margin-bottom: 10rpx; background-color: #fff; border-radius: 50%; padding: 10rpx;">
						<up-icon name="weixin-fill" color="#07C160" size="28"></up-icon>
					</view>
					<text style="color: white; ">好友</text>
				</view>
				<view class="action-item" @click="shareTimeline">
					<view style="margin-bottom: 10rpx; background-color: #fff; border-radius: 50%; padding: 10rpx;">
						<up-icon name="moments" color="#07C160" size="28"></up-icon>
					</view>
					<text style="color: white; ">朋友圈</text>
				</view>
			</view>
			<view style="margin-bottom: 120rpx; margin-top: 80rpx; color: #fff;">
				<up-icon @click="showBadgeRef = false"  name="close" color="white" size="48"></up-icon>
			</view>
		</view>
	</up-overlay>
</template>

<script setup>
	import config from '@/config/index.js'
	import {
		ref,
		watch
	} from "vue";
	import {
		onReady
	} from "@dcloudio/uni-app";
	import adcard from "@/components/adcard.vue";
	import {
		checkLogin,
		getUserInfoApi,
		videoListApi,
		videoDetailApi,
		getCode
	} from '@/api/index.js'
	import {
		http
	} from 'uview-plus';
	const fileList1 = ref([]);
	onReady(() => {
		getNewRecord()
		getUserInfo()
		videoList()
	})

	function jump() {
		toLogin();
	}

	function getAgeFromString(birthStr) {
		// birthStr 格式: "YYYY-MM-DD"
		const [year, month, day] = birthStr.split('-').map(Number);
		const today = new Date();
		const birthDate = new Date(year, month - 1, day); // 月份从0开始
		let age = today.getFullYear() - birthDate.getFullYear();
		const m = today.getMonth() - birthDate.getMonth();

		if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
			age--; // 还没过生日，减1岁
		}
		return age + '岁';
	}
	
	// 保存到相册
	const posterImg = ref('')
	const saveLocal = () => {
	    doSaveImage()
	}
	
	const doSaveImage = () => {
		if(!posterImg.value) return uni.$u.toast('暂无海报')
	  uni.saveImageToPhotosAlbum({
	    filePath: posterImg.value,
	    success: () => {
	      uni.$u.toast('已保存到相册')
	    },
	    fail: (err) => {
	      console.error(err)
	      uni.$u.toast('保存失败')
	    }
	  })
	}

	
	// 分享给好友
	const shareFriend = () => {
	  if(!posterImg.value) return uni.$u.toast('暂无海报')
	  uni.share({
	    provider: 'weixin',
	    scene: 'WXSceneSession', // 好友
	    type: 2,
	    imageUrl: posterImg.value,
	    success: () => uni.$u.toast('分享成功'),
	    fail: () => uni.$u.toast('分享失败')
	  })
	}
	
	// 分享到朋友圈
	const shareTimeline = () => {
	  if(!posterImg.value) return uni.$u.toast('暂无海报')
	  uni.share({
	    provider: 'weixin',
	    scene: 'WXSceneTimeline', // 朋友圈
	    type: 2,
	    imageUrl: posterImg.value,
	    success: () => uni.$u.toast('分享成功'),
	    fail: () => uni.$u.toast('分享失败')
	  })
	}


	// 查询最新的用户检测记录
	const visionData = ref({})
	const getNewRecord = () => {
		checkLogin().then(res => {
			if (!res.data) {
				uni.redirectTo({
					url: `/pages/tips/index`
				})
				return
			}
			if (res.code === 200) {
				visionData.value = res.data
			}
		})
	}

	const videoData = ref([])

	const videoList = () => {
		videoListApi({
			size: 100,
			page: 0
		}).then(res => {
			if (res.code === 200) {
				videoData.value = res.data.content

				const requests = videoData.value.map(item =>
					videoDetailApi(item.id).then(r => ({
						id: item.id,
						detail: r.data // 用 detail 字段装详情
					}))
				)

				Promise.all(requests)
					.then(results => {
						// 把 detail 合并回 videoData
						videoData.value = videoData.value.map(item => {
							const match = results.find(r => r.id === item.id)
							return {
								...item,
								detail: match ? match.detail : null
							}
						})
						console.log("合并后的视频数据:", videoData.value)
					})
					.catch(err => {
						console.error("详情请求失败:", err)
					})
			}
		})
	}



	//  获取用户基础信息
	const userInfo = ref({
		imageUrl: '',
		registerDate: '',
		nickName: ''
	})
	const getUserInfo = () => {
		getUserInfoApi().then(res => {
			if (res.code === 200) {
				userInfo.value = res.data
				uni.setStorageSync('userInfo', userInfo.value)
			}
		})
	}

	function toDetails(detail) {
		uni.navigateTo({
			url: `/pages/details/index?detail=${JSON.stringify(detail)}`
		})
	}

	// 新增图片
	const afterRead = async (event) => {
		// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
		let lists = [].concat(event.file);
		let fileListLen = fileList1.value.length;
		lists.map((item) => {
			fileList1.value.push({
				...item,
				status: 'uploading',
				message: '上传中',
			});
		});
		for (let i = 0; i < lists.length; i++) {
			const result = await uploadFilePromise(lists[i].url);
			let item = fileList1.value[fileListLen];
			fileList1.value.splice(fileListLen, 1, {
				...item,
				status: 'success',
				message: '',
				url: result,
			});
			fileListLen++;
		}
	};

	const uploadFilePromise = (url) => {
		return new Promise((resolve, reject) => {
			let a = uni.uploadFile({
				url: config.http_host + '/api/manage/upload', // 仅为示例，非真实的接口地址
				filePath: url,
				name: 'file',

				success: (res) => {
					setTimeout(() => {
						resolve(res.data.data);
					}, 1000);
				},
			});
		});
	};

	const activeNav = ref(uni.getStorageSync('activeNav') || 1)
	if (activeNav.value !== 1) {
		uni.redirectTo({
			url: '/pages/person/index'
		})
	}
	const changeNav = (nav) => {
		activeNav.value = nav
		uni.setStorageSync('activeNav', nav)
		if (nav === 2) {
			uni.redirectTo({
				url: '/pages/person/index'
			})
		}
	}

	const showBadgeRef = ref(false)
	// 获取海报
	const showBadge = () => {
		getCode({objectType: 'poster'}).then(res => {
			if(res.data.length > 0) {
				posterImg.value = res.data[0]
			}
			showBadgeRef.value = true
		})
	}
</script>

<style lang="less" scoped>
	.poster-popup-box {
		display: flex;
		align-items: center;
		justify-content: flex-end;
		flex-direction: column;
		height: 100vh;
		width: 100vw;
	}

	.poster-popup {
		padding: 20rpx;
		background: #fff;
		border-radius: 20rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.poster-img {
		width: 100%;
		border-radius: 20rpx;
	}

	.action-btns {
		display: flex;
		justify-content: space-around;
		align-items: center;
		width: 100%;
		margin-top: 30rpx;
	}

	.action-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		font-size: 24rpx;
		color: #333;
	}


	.root {
		min-height: 100vh;
		padding-bottom: 150rpx;
		box-sizing: border-box;
		background: linear-gradient(180deg, #FAFAFA 0%, #EEEEEE 100%);

		.nav {
			position: fixed;
			width: 627rpx;
			background: #FFFFFF;
			box-shadow: 0rpx 7rpx 20rpx 0rpx rgba(10, 150, 71, 0.15);
			border-radius: 35rpx;
			left: 0;
			right: 0;
			bottom: 28rpx;
			margin: 0 auto;
			padding-top: 32rpx;
			display: flex;
			flex-direction: row;
			justify-content: space-around;
			align-items: center;

			.item {
				display: flex;
				flex-direction: column;
				justify-content: flex-start;
				align-items: center;
				row-gap: 21rpx;

				image {
					width: 49rpx;
					height: 49rpx;
				}

				.bottomline {
					width: 86rpx;
					height: 9rpx;
					background: #fff;
					border-radius: 7rpx;
				}

				.active {
					background: #0A9647;
				}
			}
		}

		.header {
			padding: 103rpx 53rpx 53rpx 63rpx;
			display: flex;
			flex-direction: row;
			justify-content: space-between;
			background-color: #0A9647;
			border-radius: 0 0 56rpx 56rpx;
			column-gap: 23rpx;

			.headimage {
				min-width: 159rpx;
				max-width: 159rpx;
				width: 159rpx;
				height: 159rpx;
				border: 4rpx solid #fff;
				border-radius: 50%;
			}

			.desc {
				flex: 1;
				display: flex;
				flex-direction: row;
				justify-content: space-between;
				align-items: center;
				flex-wrap: wrap;
				align-content: flex-start;
				column-gap: 10rpx;
				row-gap: 10rpx;

				.name {
					font-family: PingFangSC, PingFang SC;
					font-weight: 600;
					font-size: 42rpx;
					color: #FFFFFF;
					letter-spacing: 4rpx;
				}

				.time {
					font-family: DINCondensed, DINCondensed;
					font-size: 42rpx;
					color: #FFFFFF;
				}
			}
		}

		.userinfo {
			padding: 40rpx 67rpx 46rpx 67rpx;
			font-family: PingFangSC, PingFang SC;
			font-weight: 600;
			font-size: 42rpx;
			color: #000000;
			letter-spacing: 4rpx;
		}

		.infocard {
			width: 624rpx;
			background: #27A25C;
			border-radius: 37rpx;
			padding: 39rpx 0 21rpx 0;
			margin: 0 auto 72rpx auto;
			box-sizing: border-box;

			.gapline {
				width: 2rpx;
				height: 74rpx;
				background-color: #fff;
				opacity: 0.51;
			}

			.box {
				padding: 0 10rpx;

				.title {
					font-family: PingFangSC, PingFang SC;
					font-weight: 600;
					font-size: 28rpx;
					color: #FFFFFF;
					letter-spacing: 4rpx;
					margin-bottom: 18rpx;
				}

				.value {
					display: flex;
					flex-direction: row;
					justify-content: space-between;
					align-items: flex-start;
					column-gap: 10rpx;

					.content {
						flex: 1;
						text-align: center;

						.subtitle {
							font-family: PingFangSC, PingFang SC;
							font-weight: 600;
							font-size: 21rpx;
							color: #FFFFFF;
						}

						.number {
							font-family: DINCondensed, DINCondensed;
							font-size: 28rpx;
							color: #FFFFFF;
							margin-top: 25rpx;
						}
					}
				}
			}

			.top {
				display: flex;
				flex-direction: row;
				justify-content: space-between;
				align-items: flex-end;
			}

			.bottom {
				margin-top: 56rpx;
				display: flex;
				flex-direction: row;
				justify-content: space-between;
				align-items: flex-end;
			}
		}

		.course {
			.title {
				font-family: PingFangSC, PingFang SC;
				font-weight: 600;
				font-size: 56rpx;
				color: #000000;
				letter-spacing: 4rpx;
				text-align: center;
				margin-bottom: 18rpx;
			}

			.subtitle {
				text-align: center;
				font-family: PingFangSC, PingFang SC;
				font-weight: 600;
				font-size: 32rpx;
				color: rgba(0, 0, 0, 0.5);
				letter-spacing: 4rpx;
				margin-bottom: 46rpx;
			}

			.course-card {
				width: 624rpx;
				padding: 28rpx 39rpx 28rpx 42rpx;
				box-sizing: border-box;
				background-color: #fff;
				border-radius: 28rpx;
				margin: 0 auto 28rpx auto;
				display: flex;
				flex-direction: row;
				justify-content: space-between;
				align-items: center;
				column-gap: 26rpx;

				image {
					min-width: 123rpx;
					width: 123rpx;
					max-width: 123rpx;
					height: 123rpx;
					border-radius: 7rpx;
				}

				.desc {
					flex: 1;
					height: 123rpx;

					.name {
						font-family: PingFangSC, PingFang SC;
						font-weight: 600;
						font-size: 28rpx;
						color: #000000;
						width: 320rpx;
						overflow: hidden;
						white-space: nowrap;
						text-overflow: ellipsis;
					}

					.tips {
						margin-top: 18rpx;
						font-family: PingFangSC, PingFang SC;
						font-weight: 400;
						font-size: 21rpx;
						color: #A5A5A5;
						text-overflow: ellipsis;
						display: -webkit-box;
						-webkit-box-orient: vertical;
						-webkit-line-clamp: 2;
						overflow: hidden;
					}
				}

				.status {
					min-width: 75rpx;
					width: 75rpx;
					max-width: 75rpx;
					height: 75rpx;
					background: #347952;
					border-radius: 50%;
					display: flex;
					flex-direction: row;
					justify-content: center;
					align-items: center;
				}
			}
		}

		.badge-card {
			width: 624rpx;
			padding: 46rpx 40rpx 46rpx 42rpx;
			box-sizing: border-box;
			margin: 0 auto;
			background-color: #fff;
			border-radius: 37rpx;

			.top {
				display: flex;
				flex-direction: row;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 56rpx;

				.item {
					width: 55rpx;
					height: 83rpx;
				}
			}

			.tips {
				text-align: center;
				font-family: PingFangSC, PingFang SC;
				font-weight: 600;
				font-size: 32rpx;
				color: rgba(52, 121, 82, 0.57);
				letter-spacing: 2rpx;
			}
		}
	}

	.show-badge {
		margin: 0 auto;
		width: 280rpx;
		text-align: center;
		border-radius: 30rpx;
		padding: 10rpx;
		color: white;
		font-weight: 700;
		background-color: #347952;
	}
</style>